package com.shivandragon.utils;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.shivandragon.utils.AuthorizationManager.Authorization;

public class PrezFilter implements Filter {
	
	private AuthorizationManager authorizationManager = new AuthorizationManager();

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
		Authorization authorisation = authorizationManager.getAuthorisation((HttpServletRequest) request);
		if(authorisation == null) {
			((HttpServletResponse)response).sendError(HttpServletResponse.SC_NOT_FOUND);
		} else {
			HttpServletResponse hsr = (HttpServletResponse) response;
			hsr.setHeader("Pragma", "No-cache");
			hsr.setHeader("Cache-Control", "no-cache,no-store,max-age=0");
			if(authorisation.equals(Authorization.ADMIN)) {
				((HttpServletRequest)request).getSession().setAttribute("a", Constants.ADMIN_TOKEN);
			} else if(authorisation.equals(Authorization.VIEWER)) {
				((HttpServletRequest)request).getSession().setAttribute("v", Constants.VIEWER_TOKEN);
			}
			chain.doFilter(request, response);
		}
		
	}

	@Override
	public void destroy() {}

}
